<template>
	<div>
		<div class="map-container" ref="map"></div>
		<!--		<div id="popup" class="ol-popup">-->
		<!--			<a href="#" id="popup-closer" class="ol-popup-closer"></a>-->
		<!--			<div id="popup-content"></div>-->
		<!--		</div>-->
	</div>
</template>
<script>
import uDialogModal from '../listDialog/listDialog';
import 'ol/ol.css';
import { Fill, Icon, Stroke, Style, Text } from 'ol/style';
import VectorSource from 'ol/source/Vector';
import { GeoJSON } from 'ol/format';
import VectorLayer from 'ol/layer/Vector';

import { Feature, View, Map, Overlay } from 'ol';
import { Point, Polygon } from 'ol/geom';
import CircleStyle from 'ol/style/Circle';
import { DoubleClickZoom, DragPan, MouseWheelZoom, Select } from 'ol/interaction';
import { defaults as defaultControls } from 'ol/control';

import * as olSource from 'ol/source';
import qz from '@/assets/redstar.png';
import qz1 from '@/assets/bigredstar.png';
import { createApp, h } from 'vue';
import popUp from '../flowDialog/index.vue';
import router from '@/router/index';
import * as geom from 'ol/geom';
import { getHomeData } from '../../pages/home/service';
import { bus } from '../../utils/mitt';
export default {
	data() {
		return {
			colors: ['red', 'green', 'blue'],
			map: null,
			view: null,
			styleConfig: {},
			defaultConfig: {},
			selectStyleConfig: {},
			styleSelectedDefaultConfig: {},
			options: {
				zoom: 9.8,
				center: [110.303924, 38.831719]
			},
			point: [],
			geoJSonData: null, // 要绘制的区域
			iconFeature: null, // marks
			iconVectorLayer: null //marks vectorLayer
		};
	},
	computed: {
		styleDefaultConfig: {
			// 地块样式默认设置
			get() {
				return {
					textAlign: this.styleConfig?.textAlign || 'center',
					justify: this.styleConfig?.justify || 'center',
					areaFillColor: this.styleConfig?.areaFillColor || 'rgb(143,90,47,0)',
					areaStrokeColor: this.styleConfig?.areaStrokeColor || '#f87e26',
					textFillColor: this.styleConfig?.textFillColor || '#f68121',
					textStrokeColor: this.styleConfig?.textStrokeColor || '#f68121'
				};
			},
			set() {}
		},
		// eslint-disable-next-line vue/no-dupe-keys
		styleSelectedDefaultConfig: {
			// 地块样式默认设置
			get() {
				return {
					textAlign: this.selectStyleConfig?.textAlign || 'center',
					justify: this.selectStyleConfig?.justify || 'center',
					areaFillColor: this.selectStyleConfig?.areaFillColor || 'rgb(246,174,18,0.7)',
					areaStrokeColor: this.selectStyleConfig?.areaStrokeColor || 'rgba(239,186,5,0.7)',
					textFillColor: this.selectStyleConfig?.textFillColor || '#fa0202',
					textStrokeColor: this.selectStyleConfig?.textStrokeColor || '#ecf503'
				};
			},
			set() {}
		}
	},
	created() {
		if (this.defaultConfig?.lat && this.defaultConfig?.lng) {
			this.options.center = [this.defaultConfig?.lng, this.defaultConfig?.lat];
		}
	},
	mounted() {
		this.point = this.options.center || [110.533924, 38.821719];
		this.initMap(this.options);
		this.setFlashPoint();
	},
	methods: {
		// 放大n级
		zoomIn(n) {
			let view = this.map.getView(); // 获取当前视图
			let zoom = view.getZoom(); // 获取当前缩放级别
			view.setZoom(zoom + n);
		},

		initMap(options = {}) {
			this.view = new View({
				projection: 'EPSG:4326',
				center: options.center || [110.533924, 38.821719],
				zoom: options.zoom || 12,
				maxZoom: 11,
				minZoom: 9
			});

			this.map = new Map({
				target: this.$refs.map,
				layers: [],
				controls: defaultControls({
					zoom: false,
					rotate: false,
					attribution: false
				}),
				view: this.view
			});
			this.addGeoJson('/map.geojson', 'geojsonLayer');

			const dblClickInteraction = this.map
				.getInteractions()
				.getArray()
				.find(interaction => {
					return interaction instanceof DoubleClickZoom;
				});
			this.map.removeInteraction(dblClickInteraction);
			const MouseWheelZoomInteraction = this.map
				.getInteractions()
				.getArray()
				.find(interaction => {
					return interaction instanceof MouseWheelZoom;
				});
			this.map.removeInteraction(MouseWheelZoomInteraction);
			const DragPanInteraction = this.map
				.getInteractions()
				.getArray()
				.find(interaction => {
					return interaction instanceof DragPan;
				});
			this.map.removeInteraction(DragPanInteraction);
		},
		/**
		 * 设置样式
		 */
		createStyle(feature) {
			let name = feature.values_.name;
			let styleConfig = {
				textAlign:
					name === this.selectStyleConfig.name
						? this.styleSelectedDefaultConfig.textAlign
						: this.styleDefaultConfig.textAlign,
				justify:
					name === this.selectStyleConfig.name
						? this.styleSelectedDefaultConfig.justify
						: this.styleDefaultConfig.justify,
				areaFillColor:
					name === this.selectStyleConfig.name
						? this.styleSelectedDefaultConfig.areaFillColor
						: this.styleDefaultConfig.areaFillColor,
				areaStrokeColor:
					name === this.selectStyleConfig.name
						? this.styleSelectedDefaultConfig.areaStrokeColor
						: this.styleDefaultConfig.areaStrokeColor,
				textFillColor:
					name === this.selectStyleConfig.name
						? this.styleSelectedDefaultConfig.textFillColor
						: this.styleDefaultConfig.textFillColor,
				textStrokeColor:
					name === this.selectStyleConfig.name
						? this.styleSelectedDefaultConfig.textStrokeColor
						: this.styleDefaultConfig.textStrokeColor
			};

			return new Style({
				fill: new Fill({
					color: styleConfig.areaFillColor
				}),
				stroke: new Stroke({
					color: styleConfig.areaStrokeColor,
					width: 2
				}),

				text: new Text({
					font: '12px  PingFang SC',
					textAlign: styleConfig.textAlign,
					justify: styleConfig.justify,
					text: feature.get('name'),
					fill: new Fill({
						color: styleConfig.textFillColor
					}),
					stroke: new Stroke({
						color: styleConfig.textStrokeColor,
						width: 0.1
					})
				})
			});
		},

		/**
		 *设置选中的样式
		 */
		setSelectStyle(feature) {
			return new Style({
				fill: new Fill({
					color: this.styleSelectedDefaultConfig.areaFillColor
				}),
				stroke: new Stroke({
					color: this.styleSelectedDefaultConfig.areaStrokeColor,
					width: 2
				}),
				image:
					feature.values_.geometry instanceof Point
						? new Icon({
								src: qz1, // 替换为你的图标路径
								size: [32, 32] // 定义点的大小
								// color: '#f8d006',// 定义点的颜色
						  })
						: null,

				text:
					feature.values_.geometry instanceof Point
						? new Text({
								font: '16px  PingFang SC',
								textAlign: this.styleSelectedDefaultConfig.textAlign,
								justify: this.styleSelectedDefaultConfig.justify,
								text: feature.values_.name,
								fill: new Fill({
									color: '#fa0202'
								}),
								stroke: new Stroke({
									color: this.styleSelectedDefaultConfig.textStrokeColor,
									width: 1
								}),
								offsetY: -20
						  })
						: new Text({
								font: '16px  PingFang SC',
								textAlign: this.styleSelectedDefaultConfig.textAlign,
								justify: this.styleSelectedDefaultConfig.justify,
								text: feature.values_.name,
								fill: new Fill({
									color: this.styleSelectedDefaultConfig.textFillColor
								}),
								stroke: new Stroke({
									color: this.styleSelectedDefaultConfig.textStrokeColor,
									width: 2
								})
						  })
			});
		},
		/**
		 * 添加geoGson 数据
		 */
		addGeoJson(url, layerName) {
			let source = new VectorSource({
				url: url,
				format: new GeoJSON()
			});
			const vectorLayer = new VectorLayer({
				source: source,
				style: this.createStyle,
				name: layerName
			});

			this.map.addLayer(vectorLayer);
			window.vectorLayer1 = vectorLayer;
			// if(this.selectStyleConfig?.name){
			//
			//   this.setLocationMark()
			// }.getSource().

			const changeFn = () => {
				console.log('出发方法');
				if (source.getState() === 'ready') {
					// 判定是否加载完成
					// console.log(source.getFeatures()[0].values_.id, '参数');

					if (source.getFeatures()[0].values_.id) {
						getHomeData({ id: source.getFeatures()[0].values_.id }).then(res => {
							res.dzbPoi.forEach(item => {
								this.createPoint(item.lon, item.lat);
							});
							bus.emit('aaaa', res);
							source.un('change', changeFn);
						});
					}
				}
			};
			source.on('change', changeFn);
			this.handlePolygon();
			this.ddd();

			this.setFlashPoint();
		},
		handlePolygon() {
			const polygonClick = new Select({
				style: this.setSelectStyle
			});
			this.map.addInteraction(polygonClick);
			polygonClick.on('select', e => {
				const geometry = e.selected[0].getGeometry();
				this.view.fit(geometry);
				this.loadNewGeoJson(e.selected[0].values_.id, e.selected[0].values_.name);

				this.$emit('click', e.selected, e);
			});
		},

		setLocationMark() {
			if (this.iconVectorLayer) {
				this.map.removeLayer(this.iconVectorLayer);
				this.iconVectorLayer = null;
				// return false
			}
			this.iconFeature = new Feature({
				geometry: new Point(this.point)
				// name: 'Null Island',
				// population: 4000,
				// rainfall: 500,
			});
			const iconStyle1 = new Style({
				image: new CircleStyle({
					radius: 8,
					fill: new Fill({ color: '#ecac0b' }),
					stroke: new Stroke({ color: '#fff', width: 3 }),
					size: [16, 16]
				})
			});

			this.iconFeature.setStyle(iconStyle1);
			const vectorSource = new VectorSource({
				features: [this.iconFeature]
			});

			this.iconVectorLayer = new VectorLayer({
				source: vectorSource
			});
			this.map.addLayer(this.iconVectorLayer);
		},
		setSelectStyle2(feature) {
			return new Style({
				fill: new Fill({
					color: 'rgb(246,174,18,0.7)',
				}),
				stroke: new Stroke({
					color: '#f87e26',
					width: 1
				}),
				text: new Text({
					font: '16px  PingFang SC',
					textAlign: this.styleSelectedDefaultConfig.textAlign,
					justify: this.styleSelectedDefaultConfig.justify,
					text: feature.values_.name,
					fill: new Fill({
						color: '#fa0202'
					}),
					stroke: new Stroke({
						color: '#ecf503',
						width: 1
					})
				})
			});
		},
		ddd() {
			let selected = null;
			this.map.on('pointermove', e => {
				if (selected !== null) {
					selected.setStyle(undefined);
					selected = null;
				}

				this.map.forEachFeatureAtPixel(e.pixel,  (f)=> {
					selected = f;

					f.setStyle(this.setSelectStyle2(f));
					return true;
				});
			});
		},
		setFlashPoint() {
			this.createPoint();
			this.map.on('click', event => {
				const coordinate = event.coordinate;
				// 获取点击的坐标
				this.map.forEachFeatureAtPixel(
					event.pixel,
					feature => {
						// 为点击的 feature 发送自定义的 click 消息
						try {
							router.push({
								path: '/partyBuilding',
								query: {
									id: feature?.values_.id
								}
							});
						} catch (e) {
							// let box = document.getElementsByClassName('flowDialog');
							// if (box && box.length > 0) {
							// 	for (let i = 0; i < box.length; i++) {
							// 		box[i].parentNode.removeChild(box[i]);
							// 	}
							// }
							// console.error(e);
						}
					},
					{
						layerFilter: layer => {
							return layer.get('name') === 'pointlayer';
						}
					}
				);
			});

			// function getExtent(coordinate,map) {
			// 	// 'padding' 是周围区域的半径，你可以根据需要进行调整
			// 	const padding = 100;
			// 	const radius = Math.abs(coordinate[0] - map.getCenter()[0]) + padding;
			// 	return [
			// 		[coordinate[1] - radius, coordinate[1] + radius],
			// 		[coordinate[0] - radius, coordinate[0] + radius]
			// 	];
			// }
			// this.map.on('dblclick', event => {
			// 	let coordinate = event.coordinate;
			// 	this.map.forEachFeatureAtPixel(
			// 		event.pixel,
			// 		feature => {
			// 			// 为点击的 feature 发送自定义的 click 消息
			// 			try {
			// 				console.log('双击事件触发');
			// 				uDialogModal({ type: 'img' })
			// 					.then(() => {
			// 						console.log('成功逻辑');
			// 					})
			// 					.catch(err => {
			// 						console.log('失败逻辑');
			// 					});
			// 			} catch (e) {
			// 				let box = document.getElementsByClassName('flowDialog');
			// 				if (box && box.length > 0) {
			// 					for (let i = 0; i < box.length; i++) {
			// 						box[i].parentNode.removeChild(box[i]);
			// 					}
			// 				}
			// 				console.error(e);
			// 			}
			// 		},
			// 		{
			// 			layerFilter: layer => {
			// 				return layer.get('name') === 'geojsonLayer';
			// 			}
			// 		}
			// 	);
			// });
		},
		createPoint(lon, lat) {
			let point_div = document.createElement('div');
			point_div.className = 'css_animation';
			let point_overlay = new Overlay({
				element: point_div,
				positioning: 'center-center',
				stopEvent: false
			});
			this.map.addOverlay(point_overlay);

			point_overlay.setPosition([lon, lat]);

			let point_div1 = document.createElement('div');
			point_div1.className = 'css_animation';
			let point_overlay2 = new Overlay({
				element: point_div1,
				positioning: 'center-center',
				stopEvent: false //可以传播点击事件
			});
			this.map.addOverlay(point_overlay2);

			point_overlay2.setPosition([lon, lat]);

			let feature = new Feature(new Point([lon, lat])); // 替换为你的坐标
			feature.setProperties({ id: 1, name: '沙河母村党支部' });
			feature.setStyle(
				new Style({
					image: new Icon({
						src: qz, // 替换为你的图标路径
						size: [16, 16], // 定义点的大小
						color: '#FF0000' // 定义点的颜色
					}),
					text: new Text({
						font: '12px  PingFang SC',
						textAlign: this.styleSelectedDefaultConfig.textAlign,
						justify: this.styleSelectedDefaultConfig.justify,
						text: '沙河母村',
						fill: new Fill({
							color: '#fce705'
						}),
						offsetY: -10
					})
				})
			);
			// let feature1 = new Feature(new Point([110.31706, 38.83343])); // 替换为你的坐标
			// feature1.setProperties({ id: 2, name: '四卜树村' });
			// feature1.setStyle(
			// 	new Style({
			// 		image: new Icon({
			// 			src: qz, // 替换为你的图标路径
			// 			size: [16, 16], // 定义点的大小
			// 			color: '#FF0000' // 定义点的颜色
			// 		}),
			// 		text: new Text({
			// 			font: '12px  PingFang SC',
			// 			textAlign: this.styleSelectedDefaultConfig.textAlign,
			// 			justify: this.styleSelectedDefaultConfig.justify,
			// 			text: '四卜树村',
			// 			fill: new Fill({
			// 				color: '#fce705'
			// 			}),
			// 			offsetY: -10
			// 		})
			// 	})
			// );
			let vectorLayer = new VectorLayer({
				source: new olSource.Vector({
					features: [feature]
				}),
				name: 'pointlayer'
			});
			this.map.addLayer(vectorLayer);
		}
	}
};
</script>
<style lang="scss">
.map-container {
	width: 100%;
	height: 100%;
}

.ol-viewport {
	/* 完全透明 */

	/* background-color: rgba(0, 0, 0, 0); */

	/* 完全不透明 */
	background-color: rgb(0 0 0 / 0%);
}

.ol-popup {
	position: absolute;
	bottom: 12px;
	left: -50px;
	display: none;
	min-width: 200px;
	padding: 15px;
	color: #ffffff;
	background-color: #ec9016;
	filter: drop-shadow(0 1px 4px rgb(0 0 0 / 20%));
	filter: drop-shadow(0 1px 4px #ffc125);
	border: 1px solid #bd2424;
	border-radius: 10px;
}

.ol-popup::after,
.ol-popup::before {
	position: absolute;
	top: 100%;
	width: 0;
	height: 0;
	pointer-events: none;
	content: ' ';
	border: solid transparent;
}

.ol-popup::after {
	left: 48px;
	margin-left: -10px;
	border-width: 10px;
	border-top-color: #ef9205;
}

.ol-popup::before {
	left: 48px;
	margin-left: -11px;
	border-width: 11px;
	border-top-color: #f11515;
}

.ol-popup-closer {
	position: absolute;
	top: 2px;
	right: 8px;
	color: red;
	text-decoration: none;
}

.ol-popup-closer::after {
	content: '✖';
}
.css_animation {
	height: 100px;
	width: 100px;
	border-radius: 50%;
	background: rgba(255, 196, 0, 0.9);
	transform: scale(0);
	animation: myfirst 3s;
	animation-iteration-count: infinite;
}
@keyframes myfirst {
	to {
		transform: scale(0.5);
		background: rgba(0, 0, 0, 0);
	}
}
</style>
